package study.kit.uitls;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Tuple;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public class FormatUtils {

    public static String getHeaderJsonV1(Class<?> clazz) {
        //
        Field[] farray = ReflectUtil.getFields(clazz);
        //
        Map<String, Integer> orderMap = MapUtil.createMap(HashMap.class);     // 顺序
        Map<String, String> nameMap = MapUtil.createMap(LinkedHashMap.class); // 名称
        for (Field f : farray) {
            if (!AnnotationUtil.hasAnnotation(f, ExcelHeader.class)) {
                continue;
            }
            ExcelHeader header = AnnotationUtil.getAnnotation(f, ExcelHeader.class);
            orderMap.put(f.getName(), header.order());
            nameMap.put(f.getName(), header.value());
        }
        // 排序
        log.info(">>>>>> {}", orderMap);
        log.info(">>>>>> {}", nameMap);
        log.info(">>>>>> {}", MapUtil.sortByValue(orderMap, false));
        Map<String, String> dd = MapUtil.sortByValue(orderMap, false)
                .keySet()
                .stream()
                .collect(Collectors.toMap(Function.identity(), e -> MapUtil.getStr(nameMap, e), (k1, k2) -> k1, LinkedHashMap::new));
        return JSONUtil.toJsonStr(dd);
    }

    public static String getHeaderJsonV2(Class<?> clazz) {
        //
        Field[] farray = ReflectUtil.getFields(clazz);
        //
        List<Tuple> list = ListUtil.toList();
        for (Field f : farray) {
            if (!AnnotationUtil.hasAnnotation(f, ExcelHeader.class)) {
                continue;
            }
            ExcelHeader header = AnnotationUtil.getAnnotation(f, ExcelHeader.class);
            list.add(new Tuple(f.getName(), header.value(), header.order()));
        }
        // 排序
        log.info(">>>>>> {}", list);
        CollectionUtil.sort(list, Comparator.comparing(e -> e.get(2)));
        log.info(">>>>>> {}", list);
        //
        Map<String, String> dd = IterUtil.toMap(new LinkedHashMap<>(),
                list,
                e -> e.get(0),
                e -> e.get(1));
        return JSONUtil.toJsonStr(dd);
    }
}
